package cn.itcast.web.shiro;

import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * shiro的realm类，访问认证、授权数据
 */
public class AuthRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
     //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //转换
        UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
        String email = uptoken.getUsername();

        //调用service查询
        User user = userService.findByEmail(email);
        if (user ==null){
            return null;//报错
        }
        String password = user.getPassword();
        // 参数1：身份对象; 通过subject.getPrincipal()获取的就是这里的第一个参数
        // 参数2：告诉shiro数据库中正确的密码（shiro已经有用户输入的密码，自动校验）
        // 参数3：realm的名称，可以随便写，唯一。this.getName()获取的是默认名称

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, this.getName());

        return info;
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
